package com.wuseguang.springcloud.controller;


import com.wuseguang.springcloud.dao.jdbc.ParentJdbc;
import com.wuseguang.springcloud.dao.repository.CommodityRepository;
import com.wuseguang.springcloud.dao.repository.OrderRepository;
import com.wuseguang.springcloud.dao.repository.ParentRepository;
import com.wuseguang.springcloud.entity.Commodity;
import com.wuseguang.springcloud.entity.Orders;
import com.wuseguang.springcloud.entity.Parent;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.wxpay.sdk.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxpay")
public class WechatPaymentCallback {


    protected static final Logger logger = LoggerFactory.getLogger(WechatPaymentCallback.class);
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private ParentJdbc parentJdbc;
    @Autowired
    private CommodityRepository commodityRepository;
    @Autowired
    private ParentRepository parentRepository;

    @RequestMapping(value = "notify", produces = "application/json;charset=UTF-8")
    public String payNotifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("支付回调开始");
        BufferedReader reader = null;

        reader = request.getReader();
        String line = "";
        String xmlString = null;
        StringBuffer inputString = new StringBuffer();

        while ((line = reader.readLine()) != null) {
            inputString.append(line);
        }
        xmlString = inputString.toString();
        request.getReader().close();
        logger.info("----接收到的数据如下：---" + xmlString);
        Map<String, String> map = new HashMap<String, String>();
        map = WXPayUtil.xmlToMap(xmlString);
        //支付结果
        String result_code = map.get("result_code");
        //商户订单号
        String out_trade_no = map.get("out_trade_no");
        //SUCCESS表示商户接收通知成功并校验成功,FAIL:反之
        String return_code = map.get("return_code");
        //验证签名是否一致
        if (WXPayUtil.isSignatureValid(xmlString, "344ce5d911234c0f9abae2d9d3f33462")) {
            //查询订单详情
            Orders order = orderRepository.findOutTradeNo(out_trade_no);
            if ("SUCCESS".equals(result_code)) {
                logger.info("支付成功");
                order.setTransactionStatus(2);

                //查询商品名称
                Commodity commodity = commodityRepository.findById(order.getCommodityId()).get();



                //修改会员到期时间
                Parent parent = parentRepository.findById(order.getUserId()).get();
                //修改时间
                if(StringUtils.isEmpty(parent.getDueDate())||parent.getDueDate().getTime()<System.currentTimeMillis()){
                    parent.setDueDate(DateUtil.addMonth(commodity.getMonth()));
                }else {
                    parent.setDueDate(DateUtil.addMonth(parent.getDueDate(),commodity.getMonth()));

                }
                parentRepository.save(parent);

            } else {
                logger.info("支付失败");
                order.setTransactionStatus(1);
            }
            orderRepository.save(order);

            //告知腾讯已经接受到信息了
            return returnXML(result_code);
        } else {
            return returnXML("FAIL");
        }


    }


    private String returnXML(String return_code) {

        return "<xml><return_code><![CDATA["

                + return_code

                + "]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }


}
